import os

# dir_path = input("输入要调整的目录 ")
dir_path = r"D:\00快速保存"

ext_hex_list = ['ffd8ff', '89504e47', '47494638', '464c56010500000009']  # jpg png gif flv


def get_ext(str1):
    r_ext = ""
    for i, hex_case in enumerate(ext_hex_list):
        if str1.startswith(hex_case):
            match i:
                case 0:
                    r_ext = ".jpg"
                case 1:
                    r_ext = ".png"
                case 2:
                    r_ext = ".gif"
                case 3:
                    r_ext = ".flv"
    if r_ext == "":
        if str1[8:16] == "66747970":
            r_ext = ".mp4"
    return r_ext


if os.path.exists(dir_path):
    fname_list = os.listdir(dir_path)
    sum = 0
    for x in fname_list:
        full_path = os.path.join(dir_path, x)
        if os.path.isfile(full_path):
            with open(full_path, "rb") as f:
                s = f.read(10)
                f.close()
            hex_str = ""
            for h in s:
                t = hex(h)[2:]
                if len(t) == 1:
                    t = "0" + t
                hex_str += t
            # print(x)
            real_ext = get_ext(hex_str)
            if real_ext != "":
                main_name, old_ext = os.path.splitext(full_path)
                if real_ext != old_ext.lower():
                    new_name = main_name + real_ext
                    sum += 1
                    print("\n错误", full_path)
                    print("改为", new_name)
                    try:
                        os.rename(full_path, new_name)
                    except Exception as e:
                        print("修改失败")
                        print(e)
    print("修改文件数", sum)
else:
    print("没有找到目录")
